package com.wenlin.myproduction.widget;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.icu.text.SimpleDateFormat;
import android.os.CountDownTimer;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.ColorInt;
import androidx.annotation.Nullable;

import com.wenlin.myproduction.R;
import com.wenlin.myproduction.bean.TimeBean;
import com.wenlin.myproduction.util.LogUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 时间控件，显示当前时间，小时数：分钟数，并增加渐显动画
 */
public class TimeView extends View {
    private static float RADIUS = 8;//分号的圆点的半径
    private static final long ANIM_DUR = 1000;
    private List<TimeBean> list;
    private Paint paint;
    private TextPaint textPaint;
    private Rect rect;
    private Bitmap bitmap;
    private float singleNumHeight;
    private float singleNumWidth;
    private float offset;
    private ValueAnimator valueAnimator;
    private float distance;//动画：移动的距离
    private ValueAnimator valueAnimatorAlpha;
    private int alpha;//动画：透明度
    private ValueAnimator valueAnimatorAlphaPic;
    private int alphaPic;//动画：透明度
    private CountDownTimer timer;
    private boolean showLastNum;//是否显示最后一个数字
    private boolean showAnimAlready;//是否已经动画完成
    private boolean showPicAnimAlready;//是否图片已经动画完成

    @ColorInt
    private int colorBlack = Color.parseColor("#ff5a5a5a");

    public TimeView(Context context) {
        this(context, null);
    }

    public TimeView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TimeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    /**
     * 初始化工具
     */
    private void init() {
        paint = new Paint();
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setColor(colorBlack);
        paint.setAntiAlias(true);
        textPaint = new TextPaint();
        textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        textPaint.setColor(colorBlack);
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(60);//试试效果，暂定
        rect = new Rect();
        bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.slogan);

        initTime();

        //自动延时后开始动画
        timer = new CountDownTimer(500, 500) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                startMoveAnimation();
                startAlphaAnimation();
            }
        };
        timer.start();
    }

    /**
     * 初始化时间
     */
    @SuppressLint("SimpleDateFormat")
    private void initTime() {
        if (null == list) list = new ArrayList<>();
        SimpleDateFormat format = null;
        textPaint.getTextBounds("4", 0, 1, rect);
        singleNumWidth = rect.width();
        singleNumHeight = rect.height();
        offset = singleNumHeight / 4f;
        //先这样试试看
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            format = new SimpleDateFormat("HHmm");
            long current = System.currentTimeMillis();
            String timeNow = format.format(new Date(current));
            LogUtils.d("当前时间是" + timeNow);
            //这里设置xy坐标的值，分号放在最中间，然后分号两边放数字
            list.add(new TimeBean(timeNow.substring(0, 1)));
            list.add(new TimeBean(timeNow.substring(1, 2)));
            //分号就是两个点，直接用画笔滑出来就行了，省的各种字体的影响
            list.add(new TimeBean(timeNow.substring(2, 3)));
            list.add(new TimeBean(timeNow.substring(3, 4)));
        }
    }

    /**
     * 开始数字移动动画
     */
    private void startMoveAnimation() {
        if (valueAnimator != null && valueAnimator.isRunning()) {
            valueAnimator.cancel();
            valueAnimator.removeAllUpdateListeners();
            valueAnimator.removeAllListeners();
            valueAnimator = null;
        }
        //数字是从上面慢慢滑下来，在canvas是y值渐渐增加
        valueAnimator = ValueAnimator.ofFloat(0, singleNumHeight);
        valueAnimator.addUpdateListener(animation -> {
            distance = (float) animation.getAnimatedValue();
            invalidate();
        });
        valueAnimator.setDuration(ANIM_DUR);
        valueAnimator.start();
        showLastNum = true;
    }

    /**
     * 开始数字渐显动画
     */
    private void startAlphaAnimation() {
        if (valueAnimatorAlpha != null && valueAnimatorAlpha.isRunning()) {
            valueAnimatorAlpha.cancel();
            valueAnimatorAlpha.removeAllUpdateListeners();
            valueAnimatorAlpha.removeAllListeners();
            valueAnimatorAlpha = null;
        }
        //数字是从上面慢慢滑下来，在canvas是y值渐渐增加
        valueAnimatorAlpha = ValueAnimator.ofInt(0, 255);
        valueAnimatorAlpha.addUpdateListener(animation -> {
            alpha = (int) animation.getAnimatedValue();
            if (alpha == 255) showAnimAlready = true;
            invalidate();
        });
        valueAnimatorAlpha.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                startPicAlphaAnimation();
            }
        });
        valueAnimatorAlpha.setDuration(ANIM_DUR);
        valueAnimatorAlpha.start();
        showLastNum = true;
    }

    /**
     * 开始图片渐显动画
     */
    private void startPicAlphaAnimation() {
        if (valueAnimatorAlphaPic != null && valueAnimatorAlphaPic.isRunning()) {
            valueAnimatorAlphaPic.cancel();
            valueAnimatorAlphaPic.removeAllUpdateListeners();
            valueAnimatorAlphaPic.removeAllListeners();
            valueAnimatorAlphaPic = null;
        }
        //图片渐显
        valueAnimatorAlphaPic = ValueAnimator.ofInt(0, 255);
        valueAnimatorAlphaPic.addUpdateListener(animation -> {
            alphaPic = (int) animation.getAnimatedValue();
            if (alphaPic == 255) showPicAnimAlready = true;
            invalidate();
        });
        valueAnimatorAlphaPic.setDuration(ANIM_DUR);
        valueAnimatorAlphaPic.start();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //背景色，因为我的项目带背景图片，所以先加上这个
//        canvas.drawColor(colorWhite);
//        canvas.drawPoint();//这里可以用这个方法画点，我还是习惯用另外一个画圆角矩形的方法画点
        float centerX = getWidth() / 2f;
        float timeY = getHeight() / 2f;
        //这里设置一下四个数字的x
        if (centerX != 0) {
            if (null != list && list.size() == 4 && list.get(0).getY() == 0) {//这里避免重复，可以加个判断，这样设置完之后不会再进入循环了
                for (int i = 0; i < list.size(); i++) {
                    TimeBean timeBean = list.get(i);
                    if (i == 0) {//这里switch也行，这里需要多空一个分号的位置
                        timeBean.setX(centerX - 2 * singleNumWidth - singleNumWidth / 2f);
                    } else if (i == 1) {
                        timeBean.setX(centerX - singleNumWidth - singleNumWidth / 2f);
                    } else if (i == 2) {
                        timeBean.setX(centerX + singleNumWidth - singleNumWidth / 2f);
                    } else if (i == 3) {
                        timeBean.setX(centerX + 2 * singleNumWidth - singleNumWidth / 2f);
                    }
                    timeBean.setY(timeY);
                }
            }
        }
        paint.setAlpha(255);
        //上面的那个点
        canvas.drawRoundRect(centerX - RADIUS / 2f, timeY - offset - RADIUS / 2f,
                centerX + RADIUS / 2f, timeY - offset + RADIUS / 2f, RADIUS, RADIUS, paint);//这里的5是分号上面那个点距离数字中心的偏移值，暂定
        //下面的那个点
        canvas.drawRoundRect(centerX - RADIUS / 2f, timeY + offset - RADIUS / 2f,
                centerX + RADIUS / 2f, timeY + offset + RADIUS / 2f, RADIUS, RADIUS, paint);//画时间数字，加上动画，动画就用y来控制，待会儿加
        if (null != list && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                TimeBean timeBean = list.get(i);
                textPaint.getTextBounds(timeBean.getNum(), 0, timeBean.getNum().length(), rect);
                textPaint.setAlpha(255);
                //视频中默认不显示第四个数字，动画开始才渐渐显示，前三个数字直接显示，第四个数字看情况，默认不显示，动画加载完之后显示。
                if (i == 3) {
                    if (showAnimAlready) {//动画加载完成
                        canvas.drawText(timeBean.getNum(), timeBean.getX(),
                                timeBean.getY() - (rect.bottom + rect.top) / 2f, textPaint);//- (rect.bottom + rect.top) / 2f 这个是校正微调用的
                    } else if (showLastNum) {//动画加载
                        if (valueAnimator != null && valueAnimator.isRunning())
                            textPaint.setAlpha(alpha);
                        canvas.drawText(timeBean.getNum(), timeBean.getX(),
                                timeBean.getY() - singleNumHeight + distance - (rect.bottom + rect.top) / 2f, textPaint);//- (rect.bottom + rect.top) / 2f 这个是校正微调用的
                    }
                } else {
                    canvas.drawText(timeBean.getNum(), timeBean.getX(),
                            timeBean.getY() - (rect.bottom + rect.top) / 2f, textPaint);//- (rect.bottom + rect.top) / 2f 这个是校正微调用的
                }
            }
        }
        //图片，图片的位置在中间
        if (null != bitmap) {
            if (valueAnimatorAlphaPic != null && valueAnimatorAlphaPic.isRunning())
                paint.setAlpha(alphaPic);
            else paint.setAlpha(showPicAnimAlready ? 255 : 0);
            canvas.drawBitmap(bitmap, getWidth() / 2f - bitmap.getWidth() / 2f, getHeight() / 2f + singleNumHeight, paint);//暂定
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        //用到的bitmap记得释放掉资源
        if (null != bitmap && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (valueAnimator != null && valueAnimator.isRunning()) {
            valueAnimator.cancel();
            valueAnimator.removeAllUpdateListeners();
            valueAnimator.removeAllListeners();
            valueAnimator = null;
        }
        if (valueAnimatorAlpha != null && valueAnimatorAlpha.isRunning()) {
            valueAnimatorAlpha.cancel();
            valueAnimatorAlpha.removeAllUpdateListeners();
            valueAnimatorAlpha.removeAllListeners();
            valueAnimatorAlpha = null;
        }
        if (valueAnimatorAlphaPic != null && valueAnimatorAlphaPic.isRunning()) {
            valueAnimatorAlphaPic.cancel();
            valueAnimatorAlphaPic.removeAllUpdateListeners();
            valueAnimatorAlphaPic.removeAllListeners();
            valueAnimatorAlphaPic = null;
        }
        if (list != null) {
            list.clear();
            list = null;
        }
    }
}
